using System;
using System.Runtime.Serialization;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace Servlets.Server
{
	public class Serializer
	{
		public void Serialize(string sessionId, string key, object val) {
			string folder = String.Format("sessions/{0}", sessionId);
			Directory.CreateDirectory(folder);
			string path = String.Format("{0}/{1}.object", folder, key);
			using(Stream s = File.Open(path, FileMode.Create)) {
				BinaryFormatter formatter = new BinaryFormatter();
				formatter.Serialize(s, val);
			}
		}
		
		public object Deserialize(string sessionId, string key) {
			string path = String.Format("sessions/{0}/{1}.object", sessionId, key);
			if(!File.Exists(path)) {
				throw new Exceptions.InvalidKeyException(key);
			}
			
			using(Stream s = File.Open(path, FileMode.Open)) {
				BinaryFormatter formatter = new BinaryFormatter();
				return formatter.Deserialize(s);
			}
		}
	}
}

